package wang.xinqiu.mysqlcontrol.ui

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.filled.Create
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import wang.xinqiu.mysqlcontrol.data.ConnectionInfo
import wang.xinqiu.mysqlcontrol.data.MySQLManager
import wang.xinqiu.mysqlcontrol.data.PreferencesManager
import android.util.Log
import androidx.compose.material.icons.filled.Settings
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DatabaseScreen(
    connectionInfo: ConnectionInfo,
    mysqlManager: MySQLManager,
    onBack: () -> Unit,
    onDatabaseSelected: (String) -> Unit,
    onTableViewSelected: (String, String) -> Unit = { _, _ -> },
    onTableDesignSelected: (String, String?, Boolean) -> Unit = { _, _, _ -> },
    onTableInfoSelected: (String, String) -> Unit = { _, _ -> },
    onSessionExpired: () -> Unit
) {
    val context = LocalContext.current
    val preferencesManager = remember { PreferencesManager(context) }
    
    var databases by remember { mutableStateOf<List<String>>(emptyList()) }
    var tables by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedDatabase by remember { mutableStateOf<String?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var isLoadingTables by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var showExitDialog by remember { mutableStateOf(false) }
    var selectedBottomTab by remember { mutableStateOf(0) }
    
    // 加载数据库列表
    LaunchedEffect(Unit) {
        Log.d("DatabaseScreen", "开始加载数据库列表")
        val result = mysqlManager.listDatabases()
        isLoading = false
        if (result.isSuccess) {
            databases = result.getOrNull() ?: emptyList()
            Log.d("DatabaseScreen", "成功加载 ${databases.size} 个数据库")
        } else {
            errorMessage = result.exceptionOrNull()?.message
            Log.e("DatabaseScreen", "加载数据库失败: $errorMessage")
            if (errorMessage?.contains("会话已过期") == true) {
                onSessionExpired()
            }
        }
    }
    
    // 加载选中数据库的表列表
    LaunchedEffect(selectedDatabase) {
        selectedDatabase?.let { database ->
            isLoadingTables = true
            val result = mysqlManager.listTables(database)
            isLoadingTables = false
            if (result.isSuccess) {
                tables = result.getOrNull() ?: emptyList()
            } else {
                if (result.exceptionOrNull()?.message?.contains("会话已过期") == true) {
                    onSessionExpired()
                }
            }
        }
    }

    Scaffold(
        topBar = {
            Column {
                TopAppBar(
                    title = { Text("数据库管理") },
                    navigationIcon = {
                        IconButton(onClick = { showExitDialog = true }) {
                            Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                        }
                    },
                    actions = {
                        IconButton(onClick = { 
                            // 刷新当前选中的内容
                            when (selectedBottomTab) {
                                0 -> {
                                    isLoading = true
                                    (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                                        val result = mysqlManager.listDatabases()
                                        isLoading = false
                                        if (result.isSuccess) {
                                            databases = result.getOrNull() ?: emptyList()
                                        }
                                    }
                                }
                                1 -> {
                                    selectedDatabase?.let { database ->
                                        isLoadingTables = true
                                        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                                            val result = mysqlManager.listTables(database)
                                            isLoadingTables = false
                                            if (result.isSuccess) {
                                                tables = result.getOrNull() ?: emptyList()
                                            }
                                        }
                                    }
                                }
                            }
                        }) {
                            Icon(Icons.Default.Refresh, contentDescription = "刷新")
                        }
                    }
                )
                SessionStatusBar(
                    mysqlManager = mysqlManager
                )
            }
        },
        bottomBar = {
            NavigationBar {
                NavigationBarItem(
                    icon = { Icon(Icons.Default.Storage, contentDescription = null) },
                    label = { Text("数据库") },
                    selected = selectedBottomTab == 0,
                    onClick = { selectedBottomTab = 0 }
                )
                NavigationBarItem(
                    icon = { Icon(Icons.Default.TableChart, contentDescription = null) },
                    label = { Text("表列表") },
                    selected = selectedBottomTab == 1,
                    onClick = { selectedBottomTab = 1 },
                    enabled = selectedDatabase != null
                )
                NavigationBarItem(
                    icon = { Icon(Icons.Default.Add, contentDescription = null) },
                    label = { Text("新建查询") },
                    selected = selectedBottomTab == 2,
                    onClick = { 
                        selectedBottomTab = 2
                    },
                    enabled = selectedDatabase != null // 需要选中数据库才能启用
                )
                NavigationBarItem(
                    icon = { Icon(Icons.Default.Info, contentDescription = null) },
                    label = { Text("数据库信息") },
                    selected = selectedBottomTab == 3,
                    onClick = { selectedBottomTab = 3 }
                )
            }
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            when (selectedBottomTab) {
                0 -> DatabaseListContent(
                    databases = databases,
                    isLoading = isLoading,
                    errorMessage = errorMessage,
                    selectedDatabase = selectedDatabase,
                    onDatabaseSelected = { database ->
                        selectedDatabase = database
                        selectedBottomTab = 1 // 自动切换到表列表
                    }
                )
                1 -> TableListContent(
                    selectedDatabase = selectedDatabase,
                    tables = tables,
                    isLoading = isLoadingTables,
                    onTableSelected = { table ->
                        selectedDatabase?.let { database ->
                            onTableViewSelected(database, table)
                        }
                    },
                    onTableDesignSelected = { table, isEdit ->
                        selectedDatabase?.let { database ->
                            onTableDesignSelected(database, table, isEdit)
                        }
                    },
                    onTableInfoSelected = { table ->
                        selectedDatabase?.let { database ->
                            onTableInfoSelected(database, table)
                        }
                    }
                )
                2 -> {
                    // 新建查询页面 - 需要选中数据库
                    if (selectedDatabase != null) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(16.dp)
                            ) {
                                Icon(
                                    Icons.Default.Add,
                                    contentDescription = null,
                                    modifier = Modifier.size(48.dp),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                                Text(
                                    "新建查询 - $selectedDatabase",
                                    style = MaterialTheme.typography.headlineSmall
                                )
                                Button(
                                    onClick = { onDatabaseSelected(selectedDatabase!!) }
                                ) {
                                    Text("开始查询")
                                }
                            }
                        }
                    } else {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text("请先选择数据库")
                        }
                    }
                }
                3 -> DatabaseInfoContent(
                    mysqlManager = mysqlManager,
                    onSessionExpired = onSessionExpired
                )
            }
        }
    }

    // 退出确认弹窗
    if (showExitDialog) {
        AlertDialog(
            onDismissRequest = { showExitDialog = false },
            title = { Text("关闭会话") },
            text = { Text("确定要关闭当前会话并返回登录界面吗？") },
            confirmButton = {
                TextButton(
                    onClick = {
                        showExitDialog = false
                        preferencesManager.clearLastConnection()
                        onBack()
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(onClick = { showExitDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun DatabaseListContent(
    databases: List<String>,
    isLoading: Boolean,
    errorMessage: String?,
    selectedDatabase: String?,
    onDatabaseSelected: (String) -> Unit
) {
    Box(modifier = Modifier.fillMaxSize()) {
        when {
            isLoading -> {
                CircularProgressIndicator(
                    modifier = Modifier.align(Alignment.Center)
                )
            }
            errorMessage != null -> {
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Text(
                        text = "错误: $errorMessage",
                        modifier = Modifier.padding(16.dp),
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                }
            }
            databases.isEmpty() -> {
                Text(
                    text = "没有找到数据库",
                    modifier = Modifier.align(Alignment.Center)
                )
            }
            else -> {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(databases) { database ->
                        DatabaseItem(
                            databaseName = database,
                            isSelected = database == selectedDatabase,
                            onClick = { onDatabaseSelected(database) }
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun TableListContent(
    selectedDatabase: String?,
    tables: List<String>,
    isLoading: Boolean,
    onTableSelected: (String) -> Unit,
    onTableDesignSelected: (String?, Boolean) -> Unit,
    onTableInfoSelected: (String) -> Unit
) {
    if (selectedDatabase == null) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text("请先选择数据库")
        }
        return
    }
    
    Column(modifier = Modifier.fillMaxSize()) {
        // 表操作按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Button(
                onClick = { onTableDesignSelected(null, false) },
                modifier = Modifier.weight(1f)
            ) {
                Icon(Icons.Default.Create, contentDescription = null)
                Spacer(modifier = Modifier.width(4.dp))
                Text("创建新表")
            }
        }
        
        // 表列表
        when {
            isLoading -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }
            tables.isEmpty() -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text("该数据库没有表")
                }
            }
            else -> {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(horizontal = 16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(tables) { table ->
                        TableItem(
                            tableName = table,
                            onViewClick = { onTableSelected(table) },
                            onEditClick = { onTableDesignSelected(table, true) },
                            onInfoClick = { onTableInfoSelected(table) }
                        )
                    }
                }
            }
        }
    }
}

// 添加格式化函数
private fun formatBytes(bytes: Long): String {
    return when {
        bytes >= 1024L * 1024 * 1024 * 1024 -> String.format("%.2f TB", bytes / (1024.0 * 1024 * 1024 * 1024))
        bytes >= 1024L * 1024 * 1024 -> String.format("%.2f GB", bytes / (1024.0 * 1024 * 1024))
        bytes >= 1024L * 1024 -> String.format("%.2f MB", bytes / (1024.0 * 1024))
        bytes >= 1024L -> String.format("%.2f KB", bytes / 1024.0)
        else -> "$bytes B"
    }
}

private fun formatUptime(seconds: Long): String {
    val days = seconds / 86400
    val hours = (seconds % 86400) / 3600
    val minutes = (seconds % 3600) / 60
    val remainingSeconds = seconds % 60
    
    // 计算年、月、日
    val years = days / 365
    val remainingDaysAfterYears = days % 365
    val months = remainingDaysAfterYears / 30
    val remainingDays = remainingDaysAfterYears % 30
    
    return when {
        years > 0 -> {
            val parts = mutableListOf<String>()
            parts.add("${years}年")
            if (months > 0) parts.add("${months}月")
            if (remainingDays > 0) parts.add("${remainingDays}天")
            if (hours > 0) parts.add("${hours}小时")
            if (minutes > 0) parts.add("${minutes}分钟")
            if (remainingSeconds > 0) parts.add("${remainingSeconds}秒")
            parts.joinToString("")
        }
        months > 0 -> {
            val parts = mutableListOf<String>()
            parts.add("${months}月")
            if (remainingDays > 0) parts.add("${remainingDays}天")
            if (hours > 0) parts.add("${hours}小时")
            if (minutes > 0) parts.add("${minutes}分钟")
            if (remainingSeconds > 0) parts.add("${remainingSeconds}秒")
            parts.joinToString("")
        }
        days > 0 -> {
            val parts = mutableListOf<String>()
            parts.add("${days}天")
            if (hours > 0) parts.add("${hours}小时")
            if (minutes > 0) parts.add("${minutes}分钟")
            if (remainingSeconds > 0) parts.add("${remainingSeconds}秒")
            parts.joinToString("")
        }
        hours > 0 -> {
            val parts = mutableListOf<String>()
            parts.add("${hours}小时")
            if (minutes > 0) parts.add("${minutes}分钟")
            if (remainingSeconds > 0) parts.add("${remainingSeconds}秒")
            parts.joinToString("")
        }
        minutes > 0 -> {
            if (remainingSeconds > 0) {
                "${minutes}分钟${remainingSeconds}秒"
            } else {
                "${minutes}分钟"
            }
        }
        else -> "${remainingSeconds}秒"
    }
}

private fun formatMemorySize(sizeStr: String): String {
    return try {
        val size = sizeStr.toLongOrNull() ?: return sizeStr
        formatBytes(size)
    } catch (e: Exception) {
        sizeStr
    }
}

@Composable
fun DatabaseInfoContent(
    mysqlManager: MySQLManager,
    onSessionExpired: () -> Unit
) {
    val cachedInfo by mysqlManager.databaseInfoFlow.collectAsState()
    var isLoading by remember { mutableStateOf(cachedInfo == null) }
    
    LaunchedEffect(cachedInfo) {
        isLoading = cachedInfo == null
    }
    
    if (isLoading) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                CircularProgressIndicator()
                Text("正在获取数据库信息...")
            }
        }
    } else {
        cachedInfo?.let { info ->
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 显示最后更新时间
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer
                        )
                    ) {
                        Text(
                            text = "最后更新: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(info.lastUpdated))}",
                            modifier = Modifier.padding(16.dp),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
                
                // 系统信息
                item {
                    DatabaseInfoCard(
                        title = "系统信息",
                        items = info.systemInfo
                    )
                }
                
                // 系统变量
                info.systemVariables.forEach { (category, variables) ->
                    item {
                        DatabaseInfoCard(
                            title = category,
                            items = variables
                        )
                    }
                }
            }
        } ?: run {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Text(
                    text = "无法获取数据库信息",
                    modifier = Modifier.padding(16.dp),
                    color = MaterialTheme.colorScheme.onErrorContainer
                )
            }
        }
    }
}

@Composable
fun DatabaseItem(
    databaseName: String,
    isSelected: Boolean = false,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) 
                MaterialTheme.colorScheme.primaryContainer 
            else 
                MaterialTheme.colorScheme.surface
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.Default.Storage,
                contentDescription = null,
                tint = if (isSelected) 
                    MaterialTheme.colorScheme.onPrimaryContainer 
                else 
                    MaterialTheme.colorScheme.primary
            )
            Spacer(modifier = Modifier.width(16.dp))
            Text(
                text = databaseName,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.weight(1f),
                color = if (isSelected) 
                    MaterialTheme.colorScheme.onPrimaryContainer 
                else 
                    MaterialTheme.colorScheme.onSurface
            )
            if (isSelected) {
                Icon(
                    Icons.Default.CheckCircle,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onPrimaryContainer
                )
            } else {
                Icon(
                    Icons.Default.ChevronRight,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
fun TableItem(
    tableName: String,
    onViewClick: () -> Unit,
    onEditClick: () -> Unit,
    onInfoClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    Icons.Default.TableChart,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.width(16.dp))
                Text(
                    text = tableName,
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.weight(1f)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                OutlinedButton(
                    onClick = onViewClick,
                    modifier = Modifier.weight(1f)
                ) {
                    Icon(Icons.Default.Visibility, contentDescription = null, modifier = Modifier.size(16.dp))
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("查看表", fontSize = 12.sp)
                }
                OutlinedButton(
                    onClick = onEditClick,
                    modifier = Modifier.weight(1f)
                ) {
                    Icon(Icons.Default.Edit, contentDescription = null, modifier = Modifier.size(16.dp))
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("设计表", fontSize = 12.sp)
                }
                OutlinedButton(
                    onClick = onInfoClick,
                    modifier = Modifier.weight(1f)
                ) {
                    Icon(Icons.Default.Info, contentDescription = null, modifier = Modifier.size(16.dp))
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("表结构", fontSize = 12.sp)
                }
            }
        }
    }
}

@Composable
fun DatabaseInfoCard(
    title: String,
    items: Map<String, String>
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 12.dp)
            )
            
            items.forEach { (key, value) ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = key,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.weight(1f)
                    )
                    Text(
                        text = value,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.End,
                        modifier = Modifier.weight(1f)
                    )
                }
                
                if (key != items.keys.last()) {
                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 4.dp),
                        thickness = 0.5.dp,
                        color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
                    )
                }
            }
        }
    }
}

